package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Dicitem;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Client;
import cn.wolfcode.crm.mapper.ClientMapper;
import cn.wolfcode.crm.query.ClientQueryObject;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IClientService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ClientServiceImpl implements IClientService {

    @Autowired
    private ClientMapper clientMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        clientMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Client selectByPrimaryKey(Long id) {
        return clientMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Client> selectAll() {
        return clientMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(Client entity) {
        if (entity.getId() != null){
            clientMapper.updateByPrimaryKey(entity);
        }else {
            Subject subject = SecurityUtils.getSubject();
            Employee principal = (Employee) subject.getPrincipal();

            entity.setInputDate(new Date());
            //设置创建人
            entity.setInput(principal);
            //设置负责人
            entity.setPrincipal(principal);

            Dicitem dicitem = new Dicitem();
            dicitem.setId(0L);
            //设置默认状态  : 潜在客户
            entity.setState(dicitem);
            clientMapper.insert(entity);
        }
    }
    @Override
    public PageResult query(ClientQueryObject qo) {
        Subject subject = SecurityUtils.getSubject();
        Employee principal = (Employee) subject.getPrincipal();
        if (!principal.getAdmin()){
                qo.setEmpId(principal.getId());
        }
        int total = clientMapper.query4Count(qo);
        if(total == 0 ){
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<?> rows = clientMapper.query4List(qo);
        return new PageResult(total,rows);
    }

    @Override
    public void changePrincipal(Long priId , Long id) {
        clientMapper.changePrincipal(priId,id);
    }

    @Override
    public void absorbClient(Long id) {
        Subject subject = SecurityUtils.getSubject();
        Employee principal = (Employee) subject.getPrincipal();

        Client client = clientMapper.selectByPrimaryKey(id);
        client.setPrincipal(principal);
        client.getState().setId(0L);

        clientMapper.absorbClient(client);
    }

    @Override
    public void changeState(Long stateId ,Long id) {
        clientMapper.changeState(stateId,id);
    }

}
